#include "viml/ast_detailed_printer.h"
#include <iomanip>
#include <algorithm>

namespace viml {

// MetadataCollector实现

size_t MetadataCollector::register_node(const std::string& node_type, int depth, size_t parent_id) {
    size_t id = next_id++;
    NodeMetadata metadata;
    metadata.node_type = node_type;
    metadata.unique_id = id;
    metadata.depth = depth;
    if (parent_id != 0) {
        metadata.parent_id = parent_id;
    }
    
    node_registry[id] = metadata;
    return id;
}

void MetadataCollector::set_node_position(size_t node_id, const SourcePosition& pos) {
    auto it = node_registry.find(node_id);
    if (it != node_registry.end()) {
        it->second.position = pos;
    }
}

void MetadataCollector::add_node_attribute(size_t node_id, const std::string& key, const std::string& value) {
    auto it = node_registry.find(node_id);
    if (it != node_registry.end()) {
        it->second.attributes[key] = value;
    }
}

void MetadataCollector::set_analysis_flag(size_t node_id, AnalysisFlag flag) {
    auto it = node_registry.find(node_id);
    if (it != node_registry.end()) {
        it->second.analysis_flags.insert(flag);
    }
}

void MetadataCollector::set_analysis_result(size_t node_id, const AnalysisResult& result) {
    analysis_cache[node_id] = result;
}

const NodeMetadata* MetadataCollector::get_node_metadata(size_t node_id) const {
    auto it = node_registry.find(node_id);
    return (it != node_registry.end()) ? &it->second : nullptr;
}

const AnalysisResult* MetadataCollector::get_analysis_result(size_t node_id) const {
    auto it = analysis_cache.find(node_id);
    return (it != analysis_cache.end()) ? &it->second : nullptr;
}

void MetadataCollector::analyze_expression_type(size_t node_id, ASTNode* node) {
    AnalysisResult result;
    
    // 类型推断逻辑
    if (auto num_lit = dynamic_cast<NumberLiteral*>(node)) {
        result.expression_type = "Number";
        set_analysis_flag(node_id, AnalysisFlag::IS_CONSTANT_EXPRESSION);
    } else if (auto str_lit = dynamic_cast<StringLiteral*>(node)) {
        result.expression_type = "String";
        set_analysis_flag(node_id, AnalysisFlag::IS_CONSTANT_EXPRESSION);
    } else if (auto identifier = dynamic_cast<Identifier*>(node)) {
        result.expression_type = "Variable";
        result.symbol_references[identifier->name] = "local_variable";
    } else if (auto binary_expr = dynamic_cast<BinaryExpression*>(node)) {
        // 二元表达式类型推断
        switch (binary_expr->op) {
            case BinaryExpression::Operator::ADD:
            case BinaryExpression::Operator::SUB:
            case BinaryExpression::Operator::MUL:
            case BinaryExpression::Operator::DIV:
            case BinaryExpression::Operator::MOD:
                result.expression_type = "Number";
                break;
            case BinaryExpression::Operator::EQ:
            case BinaryExpression::Operator::NE:
            case BinaryExpression::Operator::LT:
            case BinaryExpression::Operator::LE:
            case BinaryExpression::Operator::GT:
            case BinaryExpression::Operator::GE:
            case BinaryExpression::Operator::AND:
            case BinaryExpression::Operator::OR:
                result.expression_type = "Boolean";
                break;
        }
    } else if (auto call_expr = dynamic_cast<CallExpression*>(node)) {
        result.expression_type = "Function_Return";
        result.side_effects.insert("function_call");
    } else if (auto list_lit = dynamic_cast<ListLiteral*>(node)) {
        result.expression_type = "List";
        set_analysis_flag(node_id, AnalysisFlag::IS_CONSTANT_EXPRESSION);
    } else if (auto dict_lit = dynamic_cast<DictLiteral*>(node)) {
        result.expression_type = "Dict";
        set_analysis_flag(node_id, AnalysisFlag::IS_CONSTANT_EXPRESSION);
    }
    
    set_analysis_result(node_id, result);
}

void MetadataCollector::analyze_scope_info(size_t node_id, ASTNode* node) {
    auto it = analysis_cache.find(node_id);
    if (it != analysis_cache.end()) {
        if (auto func_stmt = dynamic_cast<FunctionStatement*>(node)) {
            it->second.scope_info = "function_scope";
        } else if (auto let_stmt = dynamic_cast<LetStatement*>(node)) {
            it->second.scope_info = "local_scope";
        } else {
            it->second.scope_info = "current_scope";
        }
    }
}

void MetadataCollector::analyze_complexity(size_t node_id, ASTNode* node) {
    auto it = analysis_cache.find(node_id);
    if (it != analysis_cache.end()) {
        int score = 1; // 基础复杂度
        
        if (auto binary_expr = dynamic_cast<BinaryExpression*>(node)) {
            score = 2; // 二元运算
        } else if (auto call_expr = dynamic_cast<CallExpression*>(node)) {
            score = 3 + call_expr->arguments.size(); // 函数调用复杂度
        } else if (auto if_stmt = dynamic_cast<IfStatement*>(node)) {
            score = 2 + if_stmt->then_body.size() + if_stmt->else_body.size();
        } else if (auto while_stmt = dynamic_cast<WhileStatement*>(node)) {
            score = 3 + while_stmt->body.size(); // 循环复杂度更高
        } else if (auto for_stmt = dynamic_cast<ForStatement*>(node)) {
            score = 3 + for_stmt->body.size();
        } else if (auto func_stmt = dynamic_cast<FunctionStatement*>(node)) {
            score = 5 + func_stmt->body.size(); // 函数定义复杂度
        }
        
        it->second.complexity_score = score;
        
        // 添加优化建议
        if (score > 10) {
            it->second.optimization_hints.push_back("考虑重构以降低复杂度");
        }
        if (auto func_stmt = dynamic_cast<FunctionStatement*>(node)) {
            if (func_stmt->body.size() > 20) {
                it->second.optimization_hints.push_back("函数体过长，建议拆分");
            }
        }
    }
}

void MetadataCollector::analyze_memory_usage(size_t node_id, ASTNode* node) {
    auto it = node_registry.find(node_id);
    if (it != node_registry.end()) {
        size_t base_size = sizeof(ASTNode);
        
        if (auto str_lit = dynamic_cast<StringLiteral*>(node)) {
            it->second.memory_size = base_size + str_lit->value.size();
        } else if (auto identifier = dynamic_cast<Identifier*>(node)) {
            it->second.memory_size = base_size + identifier->name.size();
        } else if (auto list_lit = dynamic_cast<ListLiteral*>(node)) {
            it->second.memory_size = base_size + list_lit->elements.size() * sizeof(void*);
        } else if (auto dict_lit = dynamic_cast<DictLiteral*>(node)) {
            it->second.memory_size = base_size + dict_lit->pairs.size() * sizeof(void*) * 2;
        } else if (auto func_stmt = dynamic_cast<FunctionStatement*>(node)) {
            size_t params_size = 0;
            for (const auto& param : func_stmt->parameters) {
                params_size += param.size();
            }
            it->second.memory_size = base_size + params_size + func_stmt->body.size() * sizeof(void*);
        } else {
            it->second.memory_size = base_size;
        }
    }
}

// ASTDetailedPrinter实现

ASTDetailedPrinter::ASTDetailedPrinter(const DetailedOutputConfig& cfg) 
    : config(cfg), current_depth(0), current_parent_id(0) {
}

void ASTDetailedPrinter::print_section_header(const std::string& title) {
    output << "==================== " << title << " ====================\n";
}

void ASTDetailedPrinter::print_section_footer() {
    output << "================================================\n";
}

void ASTDetailedPrinter::print_node_header(const NodeMetadata& metadata) {
    print_section_header("节点详情");
    output << "节点类型: " << metadata.node_type << "\n";
    output << "节点ID: #" << std::setfill('0') << std::setw(4) << metadata.unique_id << "\n";
    output << "层级深度: " << metadata.depth << "\n";
    
    if (metadata.parent_id.has_value()) {
        const auto* parent_meta = metadata_collector.get_node_metadata(metadata.parent_id.value());
        if (parent_meta) {
            output << "父节点: #" << std::setfill('0') << std::setw(4) << metadata.parent_id.value() 
                   << " (" << parent_meta->node_type << ")\n";
        }
    }
    output << "\n";
}

void ASTDetailedPrinter::print_node_footer() {
    print_section_footer();
}

void ASTDetailedPrinter::print_metadata_section(const NodeMetadata& metadata) {
    // 源码位置信息
    if (config.show_positions && metadata.position.start_line > 0) {
        output << "源码位置:\n";
        output << "  行号: " << metadata.position.start_line << ":" << metadata.position.start_col;
        if (metadata.position.end_line != metadata.position.start_line || 
            metadata.position.end_col != metadata.position.start_col) {
            output << " - " << metadata.position.end_line << ":" << metadata.position.end_col;
        }
        output << "\n";
        if (!metadata.position.source_snippet.empty()) {
            output << "  源码: \"" << metadata.position.source_snippet << "\"\n";
        }
        output << "\n";
    }
    
    // 结构信息
    output << "结构信息:\n";
    output << "  子节点数量: " << metadata.child_count << "\n";
    
    if (config.show_memory) {
        output << "  内存占用: " << format_memory_size(metadata.memory_size) << "\n";
    }
    
    if (!metadata.analysis_flags.empty()) {
        output << "  分析标志: " << format_analysis_flags(metadata.analysis_flags) << "\n";
    }
    
    // 自定义属性
    if (!metadata.attributes.empty()) {
        output << "  属性:\n";
        for (const auto& [key, value] : metadata.attributes) {
            output << "    " << key << ": " << value << "\n";
        }
    }
    output << "\n";
}

void ASTDetailedPrinter::print_analysis_section(size_t node_id) {
    if (!config.show_analysis) return;
    
    const auto* analysis = metadata_collector.get_analysis_result(node_id);
    if (!analysis) return;
    
    output << "语义信息:\n";
    
    if (config.show_types && analysis->expression_type.has_value()) {
        output << "  表达式类型: " << analysis->expression_type.value() << "\n";
    }
    
    if (!analysis->scope_info.empty()) {
        output << "  作用域: " << analysis->scope_info << "\n";
    }
    
    if (!analysis->side_effects.empty()) {
        output << "  副作用: [";
        bool first = true;
        for (const auto& effect : analysis->side_effects) {
            if (!first) output << ", ";
            output << effect;
            first = false;
        }
        output << "]\n";
    }
    
    if (analysis->complexity_score > 0) {
        output << "  复杂度评分: " << format_complexity_score(analysis->complexity_score) << "\n";
    }
    
    if (config.show_symbol_references && !analysis->symbol_references.empty()) {
        output << "  符号引用:\n";
        for (const auto& [symbol, type] : analysis->symbol_references) {
            output << "    " << symbol << " (" << type << ")\n";
        }
    }
    
    if (config.show_optimization_hints && !analysis->optimization_hints.empty()) {
        output << "  优化建议:\n";
        for (const auto& hint : analysis->optimization_hints) {
            output << "    • " << hint << "\n";
        }
    }
    
    output << "\n";
}

std::string ASTDetailedPrinter::format_analysis_flags(const std::set<AnalysisFlag>& flags) {
    std::vector<std::string> flag_names;
    for (const auto& flag : flags) {
        switch (flag) {
            case AnalysisFlag::IS_CONSTANT_EXPRESSION:
                flag_names.push_back("常量表达式");
                break;
            case AnalysisFlag::IS_PURE_FUNCTION:
                flag_names.push_back("纯函数");
                break;
            case AnalysisFlag::HAS_SIDE_EFFECTS:
                flag_names.push_back("有副作用");
                break;
            case AnalysisFlag::IS_RECURSIVE:
                flag_names.push_back("递归");
                break;
            case AnalysisFlag::CAN_BE_MEMOIZED:
                flag_names.push_back("可记忆化");
                break;
            case AnalysisFlag::IS_DEAD_CODE:
                flag_names.push_back("死代码");
                break;
            case AnalysisFlag::NEEDS_TYPE_CONVERSION:
                flag_names.push_back("需要类型转换");
                break;
        }
    }
    
    std::string result = "[";
    for (size_t i = 0; i < flag_names.size(); ++i) {
        if (i > 0) result += ", ";
        result += flag_names[i];
    }
    result += "]";
    return result;
}

std::string ASTDetailedPrinter::format_memory_size(size_t bytes) {
    if (bytes < 1024) {
        return std::to_string(bytes) + " bytes";
    } else if (bytes < 1024 * 1024) {
        return std::to_string(bytes / 1024) + " KB";
    } else {
        return std::to_string(bytes / (1024 * 1024)) + " MB";
    }
}

std::string ASTDetailedPrinter::format_complexity_score(int score) {
    std::string level;
    if (score <= 3) level = " (简单)";
    else if (score <= 7) level = " (中等)";
    else if (score <= 15) level = " (复杂)";
    else level = " (非常复杂)";
    
    return std::to_string(score) + level;
}

void ASTDetailedPrinter::print_children_header() {
    output << "============== 子节点递归展示 ================\n";
}

void ASTDetailedPrinter::print_children_footer() {
    print_section_footer();
}

bool ASTDetailedPrinter::should_show_node(const NodeMetadata& metadata) {
    if (config.max_depth >= 0 && metadata.depth > config.max_depth) {
        return false;
    }
    return true;
}

size_t ASTDetailedPrinter::visit_with_metadata(ASTNode* node, const std::string& node_type) {
    size_t node_id = metadata_collector.register_node(node_type, current_depth, current_parent_id);
    
    // 进行各种分析
    metadata_collector.analyze_expression_type(node_id, node);
    metadata_collector.analyze_scope_info(node_id, node);
    metadata_collector.analyze_complexity(node_id, node);
    metadata_collector.analyze_memory_usage(node_id, node);
    
    // 返回 node_id，但不打印
    // 打印将由调用者在添加属性后进行
    return node_id;
}

void ASTDetailedPrinter::print_node_info(size_t node_id) {
    const auto* metadata = metadata_collector.get_node_metadata(node_id);
    if (metadata && should_show_node(*metadata)) {
        print_node_header(*metadata);
        print_metadata_section(*metadata);
        print_analysis_section(node_id);
    }
}

// 基础访问者方法实现
void ASTDetailedPrinter::visit(NumberLiteral& node) {
    size_t node_id = visit_with_metadata(&node, "NumberLiteral");
    metadata_collector.add_node_attribute(node_id, "值", std::to_string(node.value));
    print_node_info(node_id);
    print_node_footer();
}

void ASTDetailedPrinter::visit(StringLiteral& node) {
    size_t node_id = visit_with_metadata(&node, "StringLiteral");
    metadata_collector.add_node_attribute(node_id, "值", "\"" + node.value + "\"");
    print_node_info(node_id);
    print_node_footer();
}

void ASTDetailedPrinter::visit(Identifier& node) {
    size_t node_id = visit_with_metadata(&node, "Identifier");
    metadata_collector.add_node_attribute(node_id, "标识符", node.name);
    print_node_info(node_id);
    print_node_footer();
}

void ASTDetailedPrinter::visit(SpecialConstantNode& node) {
    size_t node_id = visit_with_metadata(&node, "SpecialConstantNode");
    metadata_collector.add_node_attribute(node_id, "常量名", node.constant_name);
    print_node_info(node_id);
    print_node_footer();
}

void ASTDetailedPrinter::visit(BinaryExpression& node) {
    size_t node_id = visit_with_metadata(&node, "BinaryExpression");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 2;
    }
    
    metadata_collector.add_node_attribute(node_id, "运算符", BinaryExpression::operator_to_string(node.op));
    print_node_info(node_id);
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    左操作数:\n";
    node.left->accept(*this);
    
    output << "\n    右操作数:\n";
    node.right->accept(*this);
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(UnaryExpression& node) {
    size_t node_id = visit_with_metadata(&node, "UnaryExpression");
    metadata_collector.add_node_attribute(node_id, "运算符", UnaryExpression::operator_to_string(node.op));
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1;
    }
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    操作数:\n";
    node.operand->accept(*this);
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(CallExpression& node) {
    size_t node_id = visit_with_metadata(&node, "CallExpression");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1 + node.arguments.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "参数数量", std::to_string(node.arguments.size()));
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    被调用函数:\n";
    node.callee->accept(*this);
    
    if (!node.arguments.empty()) {
        output << "\n    参数列表:\n";
        for (size_t i = 0; i < node.arguments.size(); ++i) {
            output << "\n      参数 " << (i + 1) << ":\n";
            node.arguments[i]->accept(*this);
        }
    }
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(ListLiteral& node) {
    size_t node_id = visit_with_metadata(&node, "ListLiteral");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = node.elements.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "元素数量", std::to_string(node.elements.size()));
    
    if (!node.elements.empty()) {
        print_children_header();
        
        size_t old_parent = current_parent_id;
        int old_depth = current_depth;
        current_parent_id = node_id;
        current_depth++;
        
        for (size_t i = 0; i < node.elements.size(); ++i) {
            output << "\n    元素 " << (i + 1) << ":\n";
            node.elements[i]->accept(*this);
        }
        
        current_parent_id = old_parent;
        current_depth = old_depth;
        
        print_children_footer();
    } else {
        print_node_footer();
    }
}

void ASTDetailedPrinter::visit(DictLiteral& node) {
    size_t node_id = visit_with_metadata(&node, "DictLiteral");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = node.pairs.size() * 2;
    }
    
    metadata_collector.add_node_attribute(node_id, "键值对数量", std::to_string(node.pairs.size()));
    
    if (!node.pairs.empty()) {
        print_children_header();
        
        size_t old_parent = current_parent_id;
        int old_depth = current_depth;
        current_parent_id = node_id;
        current_depth++;
        
        for (size_t i = 0; i < node.pairs.size(); ++i) {
            output << "\n    键值对 " << (i + 1) << ":\n";
            output << "\n      键:\n";
            node.pairs[i].first->accept(*this);
            output << "\n      值:\n";
            node.pairs[i].second->accept(*this);
        }
        
        current_parent_id = old_parent;
        current_depth = old_depth;
        
        print_children_footer();
    } else {
        print_node_footer();
    }
}

void ASTDetailedPrinter::visit(IndexExpression& node) {
    size_t node_id = visit_with_metadata(&node, "IndexExpression");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 2;
    }
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    对象:\n";
    node.object->accept(*this);
    
    output << "\n    索引:\n";
    node.index->accept(*this);
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(LetStatement& node) {
    size_t node_id = visit_with_metadata(&node, "LetStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1;
    }
    
    metadata_collector.add_node_attribute(node_id, "变量名", node.name);
    print_node_info(node_id);
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    初始值:\n";
    node.value->accept(*this);
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(EchoStatement& node) {
    size_t node_id = visit_with_metadata(&node, "EchoStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1;
    }
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    表达式:\n";
    node.expression->accept(*this);
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(IfStatement& node) {
    size_t node_id = visit_with_metadata(&node, "IfStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1 + node.then_body.size() + node.else_body.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "then语句数", std::to_string(node.then_body.size()));
    metadata_collector.add_node_attribute(node_id, "else语句数", std::to_string(node.else_body.size()));
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    条件表达式:\n";
    node.condition->accept(*this);
    
    output << "\n    then分支:\n";
    for (size_t i = 0; i < node.then_body.size(); ++i) {
        output << "\n      语句 " << (i + 1) << ":\n";
        node.then_body[i]->accept(*this);
    }
    
    if (!node.else_body.empty()) {
        output << "\n    else分支:\n";
        for (size_t i = 0; i < node.else_body.size(); ++i) {
            output << "\n      语句 " << (i + 1) << ":\n";
            node.else_body[i]->accept(*this);
        }
    }
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(WhileStatement& node) {
    size_t node_id = visit_with_metadata(&node, "WhileStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1 + node.body.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "循环体语句数", std::to_string(node.body.size()));
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    条件表达式:\n";
    node.condition->accept(*this);
    
    output << "\n    循环体:\n";
    for (size_t i = 0; i < node.body.size(); ++i) {
        output << "\n      语句 " << (i + 1) << ":\n";
        node.body[i]->accept(*this);
    }
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(ForStatement& node) {
    size_t node_id = visit_with_metadata(&node, "ForStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1 + node.body.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "循环变量", node.variable);
    metadata_collector.add_node_attribute(node_id, "循环体语句数", std::to_string(node.body.size()));
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    可迭代对象:\n";
    node.iterable->accept(*this);
    
    output << "\n    循环体:\n";
    for (size_t i = 0; i < node.body.size(); ++i) {
        output << "\n      语句 " << (i + 1) << ":\n";
        node.body[i]->accept(*this);
    }
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(FunctionStatement& node) {
    size_t node_id = visit_with_metadata(&node, "FunctionStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = node.body.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "函数名", node.name);
    metadata_collector.add_node_attribute(node_id, "参数数量", std::to_string(node.parameters.size()));
    metadata_collector.add_node_attribute(node_id, "函数体语句数", std::to_string(node.body.size()));
    
    std::string params_str = "[";
    for (size_t i = 0; i < node.parameters.size(); ++i) {
        if (i > 0) params_str += ", ";
        params_str += node.parameters[i];
    }
    params_str += "]";
    metadata_collector.add_node_attribute(node_id, "参数列表", params_str);
    print_node_info(node_id);
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    函数体:\n";
    for (size_t i = 0; i < node.body.size(); ++i) {
        output << "\n      语句 " << (i + 1) << ":\n";
        node.body[i]->accept(*this);
    }
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(ReturnStatement& node) {
    size_t node_id = visit_with_metadata(&node, "ReturnStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = node.value ? 1 : 0;
    }
    
    if (node.value) {
        print_children_header();
        
        size_t old_parent = current_parent_id;
        int old_depth = current_depth;
        current_parent_id = node_id;
        current_depth++;
        
        output << "\n    返回值:\n";
        node.value->accept(*this);
        
        current_parent_id = old_parent;
        current_depth = old_depth;
        
        print_children_footer();
    } else {
        metadata_collector.add_node_attribute(node_id, "返回值", "无");
        print_node_footer();
    }
}

void ASTDetailedPrinter::visit(CallStatement& node) {
    size_t node_id = visit_with_metadata(&node, "CallStatement");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = 1;
    }
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    output << "\n    函数调用表达式:\n";
    node.call_expr->accept(*this);
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

void ASTDetailedPrinter::visit(Program& node) {
    size_t node_id = visit_with_metadata(&node, "Program");
    
    auto* metadata = const_cast<NodeMetadata*>(metadata_collector.get_node_metadata(node_id));
    if (metadata) {
        metadata->child_count = node.statements.size();
    }
    
    metadata_collector.add_node_attribute(node_id, "顶级语句数", std::to_string(node.statements.size()));
    
    print_children_header();
    
    size_t old_parent = current_parent_id;
    int old_depth = current_depth;
    current_parent_id = node_id;
    current_depth++;
    
    for (size_t i = 0; i < node.statements.size(); ++i) {
        output << "\n    语句 " << (i + 1) << ":\n";
        node.statements[i]->accept(*this);
    }
    
    current_parent_id = old_parent;
    current_depth = old_depth;
    
    print_children_footer();
}

} // namespace viml